// pages/index/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 用户信息
    userInfo: {
      avatarUrl: '/images/default-avatar.png',
      nickName: '记忆旅行者',
      role: 'admin' // admin 或 partner
    },
    
    // 伴侣信息
    partnerInfo: {
      avatarUrl: '/images/default-avatar.png',
      nickName: 'TA',
      isOnline: false
    },
    
    // 情感仪表盘数据
    emotionDashboard: {
      currentMood: 'calm', // happy, sad, excited, calm, anxious
      moodScore: 75,
      partnerMood: 'happy',
      partnerMoodScore: 80,
      weatherType: 'sunny', // sunny, cloudy, rainy, stormy
      weatherDesc: '心情晴朗',
      moodHistory: [] // 最近7天的心情数据
    },
    
    // 统计数据
    statistics: {
      totalCapsules: 0,
      totalMemories: 0,
      activeDays: 0,
      sharedMoments: 0,
      emotionPoints: 0
    },
    
    // 时间线数据
    timeline: {
      todayMoments: [],
      recentCapsules: [],
      upcomingEvents: []
    },
    
    // 快速创建选项
    quickActions: [
      { id: 'mood', name: '记录心情', icon: '💝', color: '#ff6b9d' },
      { id: 'memory', name: '珍藏回忆', icon: '📸', color: '#4ecdc4' },
      { id: 'voice', name: '语音胶囊', icon: '🎙️', color: '#45b7d1' },
      { id: 'future', name: '未来信件', icon: '💌', color: '#96ceb4' }
    ],
    
    // 主题相关
    currentTheme: 'admin', // admin 或 partner
    currentTab: 'home', // 当前激活的标签页
    
    // 加载状态
    loading: false,
    refreshing: false,
    
    // 动画
    containerAnimation: {},
    dashboardAnimation: {},
    
    // 导航栏状态
    isHeaderCompact: false,
    scrollTop: 0,
    headerOpacity: 1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initUserData();
    this.loadDashboardData();
    this.initAnimations();
    this.initScrollListener();
    this.startAutoRefresh();
  },

  // 初始化用户数据
  initUserData() {
    const userInfo = wx.getStorageSync('userInfo') || {};
    const currentTheme = wx.getStorageSync('currentTheme') || 'admin';
    
    this.setData({
      'userInfo.role': userInfo.role || 'admin',
      'userInfo.nickName': userInfo.nickName || '记忆旅行者',
      'userInfo.avatarUrl': userInfo.avatarUrl || '/images/default-avatar.png',
      currentTheme: currentTheme
    });
    
    // 应用主题
    this.applyTheme(currentTheme);
  },

  // 应用主题
  applyTheme(theme) {
    const themeClass = theme === 'admin' ? 'admin-theme' : 'partner-theme';
    // 这里可以动态设置页面主题类
  },

  // 初始化动画
  initAnimations() {
    const containerAnimation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease-in-out'
    });
    
    const dashboardAnimation = wx.createAnimation({
      duration: 800,
      timingFunction: 'ease-out'
    });
    
    this.setData({
      containerAnimation: containerAnimation.export(),
      dashboardAnimation: dashboardAnimation.export()
    });
  },

  // 初始化滚动监听
  initScrollListener() {
    // 获取系统信息
    const systemInfo = wx.getSystemInfoSync();
    this.screenHeight = systemInfo.windowHeight;
    this.compactThreshold = 100; // 滚动100rpx后开始收缩
  },

  // 页面滚动监听
  onPageScroll(e) {
    const scrollTop = e.scrollTop;
    const isCompact = scrollTop > this.compactThreshold;
    
    // 计算透明度和缩放比例
    const progress = Math.min(scrollTop / (this.compactThreshold * 2), 1);
    const headerOpacity = Math.max(0.95 - progress * 0.2, 0.75);
    
    if (this.data.isHeaderCompact !== isCompact || 
        Math.abs(this.data.scrollTop - scrollTop) > 10) {
      this.setData({
        isHeaderCompact: isCompact,
        scrollTop: scrollTop,
        headerOpacity: headerOpacity
      });
    }
  },

  // 加载仪表盘数据
  async loadDashboardData() {
    this.setData({ loading: true });
    
    try {
      // 并行加载多个数据源
      const [emotionData, statisticsData, timelineData] = await Promise.all([
        this.loadEmotionData(),
        this.loadStatisticsData(),
        this.loadTimelineData()
      ]);
      
      this.setData({
        emotionDashboard: emotionData,
        statistics: statisticsData,
        timeline: timelineData,
        loading: false
      });
      
      // 启动情感仪表盘动画
      this.animateDashboard();
      
    } catch (error) {
      console.error('加载仪表盘数据失败:', error);
      this.setData({ loading: false });
      wx.showToast({
        title: '数据加载失败',
        icon: 'none'
      });
    }
  },

  // 加载情感数据
  loadEmotionData() {
    return new Promise((resolve) => {
      // 模拟API调用
      setTimeout(() => {
        resolve({
          currentMood: 'happy',
          moodScore: 85,
          partnerMood: 'calm',
          partnerMoodScore: 75,
          weatherType: 'sunny',
          weatherDesc: '今天心情特别好',
          moodHistory: [
            { date: '2024-01-01', mood: 'happy', score: 80 },
            { date: '2024-01-02', mood: 'calm', score: 70 },
            { date: '2024-01-03', mood: 'excited', score: 90 }
          ]
        });
      }, 500);
    });
  },

  // 加载统计数据
  loadStatisticsData() {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          totalCapsules: 24,
          totalMemories: 156,
          activeDays: 45,
          sharedMoments: 18,
          emotionPoints: 2580
        });
      }, 300);
    });
  },

  // 加载时间线数据
  loadTimelineData() {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          todayMoments: [
            { id: 1, type: 'mood', content: '今天心情很好', time: '09:30', icon: '😊' },
            { id: 2, type: 'memory', content: '和TA一起看电影', time: '14:20', icon: '🎬' }
          ],
          recentCapsules: [
            { id: 1, title: '第一次约会', date: '2024-01-01', type: 'memory' },
            { id: 2, title: '生日惊喜', date: '2024-01-02', type: 'celebration' }
          ],
          upcomingEvents: [
            { id: 1, title: '纪念日提醒', date: '2024-01-15', type: 'anniversary' }
          ]
        });
      }, 400);
    });
  },

  // 启动自动刷新
  startAutoRefresh() {
    // 每5分钟自动刷新情感数据
    this.refreshTimer = setInterval(() => {
      this.loadEmotionData().then(data => {
        this.setData({ emotionDashboard: data });
      });
    }, 5 * 60 * 1000);
  },

  // 动画化仪表盘
  animateDashboard() {
    const animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease-out'
    });
    
    animation.scale(1.05).step();
    animation.scale(1).step();
    
    this.setData({
      dashboardAnimation: animation.export()
    });
  },

  // 快速创建操作
  onQuickAction(e) {
    const actionId = e.currentTarget.dataset.action;
    const action = this.data.quickActions.find(item => item.id === actionId);
    
    if (!action) return;
    
    switch (actionId) {
      case 'mood':
        this.recordMood();
        break;
      case 'memory':
        this.createMemory();
        break;
      case 'voice':
        this.createVoiceCapsule();
        break;
      case 'future':
        this.createFutureLetter();
        break;
      default:
        break;
    }
  },

  // 记录心情
  recordMood() {
    wx.showActionSheet({
      itemList: ['😊 开心', '😢 难过', '😴 平静', '😍 兴奋', '😰 焦虑'],
      success: (res) => {
        const moods = ['happy', 'sad', 'calm', 'excited', 'anxious'];
        const selectedMood = moods[res.tapIndex];
        
        // 更新当前心情
        this.setData({
          'emotionDashboard.currentMood': selectedMood
        });
        
        wx.showToast({
          title: '心情记录成功',
          icon: 'success'
        });
        
        // 触发心情动画
        this.animateMoodChange();
      }
    });
  },

  // 创建回忆
  createMemory() {
    wx.navigateTo({
      url: '/pages/capsule/create?type=memory'
    });
  },

  // 创建语音胶囊
  createVoiceCapsule() {
    wx.navigateTo({
      url: '/pages/voice/record'
    });
  },

  // 创建未来信件
  createFutureLetter() {
    wx.navigateTo({
      url: '/pages/capsule/create?type=future'
    });
  },

  // 心情变化动画
  animateMoodChange() {
    const animation = wx.createAnimation({
      duration: 600,
      timingFunction: 'ease-in-out'
    });
    
    animation.scale(1.2).step({ duration: 300 });
    animation.scale(1).step({ duration: 300 });
    
    this.setData({
      dashboardAnimation: animation.export()
    });
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail
    });
  },

  // 搜索
  onSearch(e) {
    const keyword = e.detail;
    console.log('搜索关键词:', keyword);
    // 实现搜索逻辑
  },

  // 清除搜索
  clearSearch() {
    this.setData({
      searchKeyword: ''
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({ refreshing: true });
    
    this.loadDashboardData().then(() => {
      this.setData({ refreshing: false });
      wx.stopPullDownRefresh();
      wx.showToast({
        title: '刷新成功',
        icon: 'success'
      });
    }).catch(() => {
      this.setData({ refreshing: false });
      wx.stopPullDownRefresh();
    });
  },

  // 导航到心情小偷中心
  onNavigateToThief() {
    wx.navigateTo({
      url: '/pages/thief/select/index'
    });
  },

  // 导航到生理期健康中心
  onNavigateToHealth() {
    wx.navigateTo({
      url: '/pages/health/index'
    });
  },

  // 导航到焦虑安抚空间
  onNavigateToAnxiety() {
    wx.navigateTo({
      url: '/pages/anxiety/index'
    });
  },

  // 导航到最终答案之锁
  onNavigateToFinalAnswer() {
    wx.navigateTo({
      url: '/pages/final-answer/index'
    });
  },

  // 底部导航切换
  onNavChange(e) {
    const tab = e.currentTarget.dataset.tab;
    
    this.setData({ currentTab: tab });
    
    switch (tab) {
      case 'home':
        // 已在首页，刷新数据
        this.loadDashboardData();
        break;
      case 'timeline':
        wx.navigateTo({
          url: '/pages/timeline/index'
        });
        break;
      case 'discover':
        wx.navigateTo({
          url: '/pages/discover/index'
        });
        break;
      case 'profile':
        wx.navigateTo({
          url: '/pages/profile/index'
        });
        break;
      default:
        break;
    }
  },

  // 创建胶囊（从底部导航）
  onCreateCapsule() {
    wx.showActionSheet({
      itemList: ['记录心情', '珍贵回忆', '语音胶囊', '未来信件'],
      success: (res) => {
        const actions = ['mood', 'memory', 'voice', 'future'];
        const selectedAction = actions[res.tapIndex];
        
        // 模拟点击快速创建
        this.onQuickAction({
          currentTarget: {
            dataset: {
              action: selectedAction
            }
          }
        });
      }
    });
  },

  // 标签切换
  onTabChange(e) {
    const tabName = e.currentTarget.dataset.name;
    this.setData({
      activeTab: tabName
    });
    this.filterCapsules(tabName);
  },

  // 筛选胶囊
  filterCapsules(tab) {
    // 实现筛选逻辑
    console.log('筛选标签:', tab);
  },

  // 胶囊点击
  onCapsulePress(e) {
    const capsule = e.currentTarget.dataset.capsule;
    wx.navigateTo({
      url: `/pages/capsule/detail/detail?id=${capsule.id}`
    });
  },

  // 更多操作
  onMoreActions(e) {
    const capsule = e.currentTarget.dataset.capsule;
    this.setData({
      currentCapsule: capsule,
      showActionSheet: true
    });
  },

  // 查看收藏
  onViewFavorites() {
    wx.navigateTo({
      url: '/pages/favorites/favorites'
    });
  },

  // 查看最近
  onViewRecent() {
    wx.navigateTo({
      url: '/pages/recent/recent'
    });
  },

  // 查看设置
  onViewSettings() {
    wx.navigateTo({
      url: '/pages/settings/settings'
    });
  },

  // 按钮按下效果
  onButtonPress(e) {
    const animation = wx.createAnimation({
      duration: 100,
      timingFunction: 'ease-in-out'
    });
    animation.scale(0.95).step();
    
    this.setData({
      createAnimation: animation.export()
    });
    
    setTimeout(() => {
      animation.scale(1).step();
      this.setData({
        createAnimation: animation.export()
      });
    }, 100);
  },

  // 加载更多
  loadMore() {
    if (this.data.loading) return;
    
    this.setData({ loading: true });
    
    // 模拟加载延迟
    setTimeout(() => {
      this.setData({
        loading: false,
        hasMore: false
      });
    }, 1000);
  },

  // 操作面板关闭
  onActionSheetClose() {
    this.setData({
      showActionSheet: false,
      currentCapsule: null
    });
  },

  // 操作面板选择
  onActionSheetSelect(e) {
    const action = e.detail.value;
    const capsule = this.data.currentCapsule;
    
    switch (action) {
      case 'edit':
        wx.navigateTo({
          url: `/pages/capsule/edit/edit?id=${capsule.id}`
        });
        break;
      case 'delete':
        this.deleteCapsule(capsule);
        break;
      case 'share':
        this.shareCapsule(capsule);
        break;
    }
    
    this.onActionSheetClose();
  },

  // 删除胶囊
  deleteCapsule(capsule) {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个时空胶囊吗？',
      success: (res) => {
        if (res.confirm) {
          // 实现删除逻辑
          console.log('删除胶囊:', capsule.id);
        }
      }
    });
  },

  // 分享胶囊
  shareCapsule(capsule) {
    wx.showShareMenu({
      withShareTicket: true
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  // onPullDownRefresh() {
  //   // 已在上面实现
  // },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})